package cn.codeforfun.user;

import cn.codeforfun.base.BaseMapper;
import cn.codeforfun.generator.mapper.UserMapper;
import cn.codeforfun.generator.model.User;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * @author wangbin
 */
@RestController
@RequestMapping("/oauth/user")
public class UserController {
    @Resource
    private UserMapper userMapper;
    @Resource
    private BaseMapper baseMapper;

    @GetMapping
    @PreAuthorize("hasAuthority('admin')")
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('admin')")
    public User selectByPrimaryKey(@PathVariable String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @PostMapping
    @PreAuthorize("hasAuthority('admin')")
    public void saveOrUpdate(@RequestBody User user) {
        if (user.getUserId() == null) {
            user.setUserId(UUID.randomUUID().toString());
            userMapper.insertSelective(user);
            baseMapper.insertRelationBetweenUserAndRole(user.getUserId(), "user");
        } else {
            userMapper.updateByPrimaryKeySelective(user);
        }
    }
}
